package com.happy3w.ssp.schoolmatehome.repository;

import com.happy3w.ssp.schoolmatehome.entity.NoteTag;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;

import java.util.List;

@Repository
public interface NoteTagRepository extends JpaRepository<NoteTag, Long> {
    List<NoteTag> findAllByNoteId(Long noteId);

    void deleteByNoteId(Long noteId);

    default List<NoteTag> persistAll(List<NoteTag> tags, Long noteId) {
        this.deleteByNoteId(noteId);
        return tags.stream()
                .map(NoteTag::getTag)
                .filter(StringUtils::hasText)
                .distinct()
                .map(tag -> {
                    NoteTag objTag = NoteTag.builder()
                            .noteId(noteId)
                            .tag(tag)
                            .build();
                    return save(objTag);
                }).toList();
    }
}